import express from 'express';
import * as articles from '../../controllers/articles.js';
// 引入JWT验证中间件
import { auth } from '../../auth/auth.js';
import initUpload from "../../util/upload.js"
// 配置multer处理form-data
const upload = initUpload();

const router = express.Router();

// 10. 文章搜索
router.get('/query', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/article/query 请求...');
    const { key, type, state, page = 1, perpage = 6 } = req.query;
    
    // 使用高级搜索函数
    const searchOptions = {
      keyword: key,
      categoryId: type,
      state: state,
      page: parseInt(page),
      pageSize: parseInt(perpage)
    };
    
    let data = await articles.advancedSearchArticles(searchOptions);
    let countResult = await articles.advancedSearchArticlesCount(searchOptions);
    let [{ count }] = countResult;
    let pages = Math.ceil(count / parseInt(perpage));
    
    res.send({
      code: 200,
      msg: "查询成功",
      pages,
      page: parseInt(page),
      data: data.map(item => ({
        id: item.id,
        title: item.title,
        intro: item.intro || "",
        cover: item.cover,
        type: item.type,
        read: item.read,
        comment: item.comments || 0,
        date: item.date,
        state: item.state || "已发布"
      }))
    });
  } catch (error) {
    console.error('文章搜索失败:', error.message);
    res.status(500).send({
      code: 500,
      msg: "搜索失败: " + error.message
    });
  }
});

// 11. 发布文章
router.post('/publish', auth(), upload.single('cover'), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/article/publish 请求...');
    console.log('请求体数据:', req.body);
    console.log('上传的文件:', req.file);
    
    // 健壮性参数校验
    let title = req.body?.title ?? "";
    let categoryId = req.body?.categoryId ?? "";
    let date = req.body?.date ?? "";
    let content = req.body?.content ?? "";
    let state = req.body?.state ?? "草稿";
    
    if (title == "" || categoryId == "" || date == "" || content == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    if (req.file) {
      console.log("http://127.0.0.1:8000/upload/" + req.file.filename); // 可地址访问图片
    }
    
    // 处理封面图片
    let cover = "/uploads/default-cover.jpg"; // 默认封面
    if (req.file) {
      cover = `/uploads/${req.file.filename}`;
    }
    
    // 添加后，插入文章
    const result = await articles.insertArticle(title, content, "管理员", parseInt(categoryId), cover, state);
    console.log('插入文章结果:', result);
    res.send({
      code: 200,
      msg: "发布成功"
    });
  } catch (error) {
    console.error('发布文章失败，详细错误:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).send({
      code: 500,
      msg: "发布失败: " + error.message
    });
  }
});

// 12. 根据id获取文章信息
router.get('/search', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/article/search 请求...');
    
    // 健壮性参数校验
    let id = req.query?.id ?? "";
    if (id == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    let articleData = await articles.selectArticleById(id);
    if (articleData.length === 0) {
      return res.status(404).send({
        code: 404,
        msg: "文章不存在"
      });
    }
    let article = articleData[0];
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        id: article.id,
        title: article.title,
        cover: article.cover,
        categoryId: article.categoryId,
        date: article.date,
        content: article.content
      }
    });
  } catch (error) {
    console.error('获取文章信息失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

// 13. 文章编辑
router.post('/edit', auth(), upload.single('cover'), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/article/edit 请求...');
    console.log('请求体数据:', req.body);
    console.log('上传的文件:', req.file);
    
    // 健壮性参数校验
    let id = req.body?.id ?? "";
    let title = req.body?.title ?? "";
    let categoryId = req.body?.categoryId ?? "";
    let date = req.body?.date ?? "";
    let content = req.body?.content ?? "";
    let state = req.body?.state ?? "草稿";
    
    if (id == "" || title == "" || categoryId == "" || date == "" || content == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    if (req.file) {
      console.log("http://127.0.0.1:8080/upload/" + req.file.filename);
    }
    console.log('准备更新文章，参数:', { id, title, content, categoryId, date, state });
    
    // 处理封面图片
    let cover = '/uploads/default-cover.jpg'; // 默认封面
    if (req.file) {
      cover = `/uploads/${req.file.filename}`;
    }
    
    await articles.updateArticle(id, title, content, "管理员", parseInt(categoryId), cover);
    res.send({
      code: 200,
      msg: "修改成功"
    });
  } catch (error) {
    console.error('编辑文章失败，详细错误:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).send({
      code: 500,
      msg: "修改失败: " + error.message
    });
  }
});

// 14. 删除文章    (假删除，idDelete置为1)
router.post('/delete', auth(), upload.none(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/article/delete 请求...');
    console.log('请求体数据:', req.body);
    
    // 健壮性参数校验
    let id = req.body?.id ?? "";
    if (id == "") {
      return res.send({
        code: 400,
        msg: "参数有误"
      });
    }
    
    console.log('准备删除文章，ID:', id);
    
    await articles.deleteArticle(id);
    res.send({
      code: 200,
      msg: "删除成功"
    });
  } catch (error) {
    console.error('删除文章失败，详细错误:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).send({
      code: 500,
      msg: "删除失败: " + error.message
    });
  }
});

export default router;
